package com.selly.hanjuang;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.selly.hanjuang.lib.JSONParser;
import com.selly.hanjuang.lib.ListAdapterTransaksi;
import com.selly.hanjuang.lib.MyApplication;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

public class MenuTransaksi extends Activity {

	// Progress Dialog
	private ProgressDialog pDialog;

	// Creating JSON Parser object
	JSONParser jParser = new JSONParser();

	ArrayList<HashMap<String, String>> DaftarProduk;

	// url http://hanjuang.0fees.net/daftar_produk.php
	//private static String url_daftar_produk = "http://10.0.2.2/hanjuang/json/daftar_produk.php";
	private static String url_daftar_produk = "http://hanjuang.web.id/json/daftar_produk.php";

	// JSON Node names
	public static final String TAG_SUCCESS = "success";
	public static final String TAG_DAFTAR_PRODUK = "daftar_produk";
	public static final String TAG_ID_PRODUK = "id_produk";
	public static final String TAG_NAMA_PRODUK = "nama_produk";
	public static final String TAG_LINK_IMAGE_PRODUK = "link_image";
	public static final String TAG_KOMPOSISI = "komposisi";
	public static final String TAG_HARGA = "harga";

	//Button ButtonAddTocart;
	
	// daftar_produk JSONArray
	JSONArray daftar_produk = null;

	ListView list;
	ListAdapterTransaksi adapter;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.menu_transaksi);
				
		// get cikan
		String msg = ((MyApplication) this.getApplication()).getStringValue();
		Log.i("INFO MyApplication", msg);
		
		// Hashmap for ListView
		DaftarProduk = new ArrayList<HashMap<String, String>>();
		
		// loading daftar 
		new LoadDaftarRumahSakitActivity().execute();
		
		// Get listview
		list = (ListView) findViewById(R.id.list);
		
		// on selecting single rumah sakit
		// launching detail rumah sakit layout
		list.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				// getting values from selected listitem
				String id_produk = ((TextView) view.findViewById(R.id.id_produk)).getText().toString();
				
				// Starting new intent
				Intent in = new Intent(getApplicationContext(), DetailProductActivity.class);
				// sending id_produk to next activity : DetailBarangActivity
				in.putExtra(TAG_ID_PRODUK, id_produk);
				
				startActivityForResult(in, 100);
			}
		});

	}

	/**
	 * Updating parsed JSON data into ListView
	 * */
	public void SetListViewAdapter(ArrayList<HashMap<String, String>> daftar) {		
		adapter = new ListAdapterTransaksi(this, daftar);
		list.setAdapter(adapter);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {

		super.onActivityResult(requestCode, resultCode, data);
		//if result code 100
		if (resultCode == 100) {
			// if result code 100 is received
			// means user edited/deleted record
			// reload this screen again
			Intent intent = getIntent();
			finish();
			startActivity(intent);
		}
	}

	/**
	 * Background Async Task to Load 
	 * all record data by making HTTP Request
	 * */
	class LoadDaftarRumahSakitActivity extends
			AsyncTask<String, String, String> {

		/**
		 * Before starting background thread show progress dialog
		 */
		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			pDialog = new ProgressDialog(MenuTransaksi.this);
			pDialog.setMessage("Mohon tunggu yah ;)");
			pDialog.setIndeterminate(false);
			pDialog.setCancelable(false);
			pDialog.show();
		}
	
		/**
		 * getting all record data from url
		 */
		@Override
		protected String doInBackground(String... arg0) {
			// TODO Auto-generated method stub
		
			// Building Parameters
			List<NameValuePair> params = new ArrayList<NameValuePair>();

			// getting JSON string from URL
			JSONObject json = jParser.makeHttpRequest(url_daftar_produk, "GET",
					params);


			// check your log cat for JSON response
			Log.d("Daftar Rumah Sakit Coy!:", json.toString());
			
			try {
				// Checking for SUCCESS TAG
				int success = json.getInt(TAG_SUCCESS);

				if (success == 1) {
					// Ada record Data (SUCCESS = 1)
					// Getting Array of daftar_produk
					daftar_produk = 
							json.getJSONArray(TAG_DAFTAR_PRODUK);
					
					// Looping through All daftar_produk
					for (int i=0; i < daftar_produk.length(); i++) {
						JSONObject c = daftar_produk.getJSONObject(i);

						
						// Storing each json item in variable
						String id_produk = c.getString(TAG_ID_PRODUK);
						String nama_produk = c.getString(TAG_NAMA_PRODUK);
						String link_image_produk = c.getString(TAG_LINK_IMAGE_PRODUK);

						String komposisi = c.getString(TAG_KOMPOSISI);
						String harga = c.getString(TAG_HARGA);
						
						// creating new HashMap
						HashMap<String, String> map = new HashMap<String, String>();

						
						// adding each child node to HashMap key => value
						map.put(TAG_ID_PRODUK, id_produk);
						map.put(TAG_NAMA_PRODUK, nama_produk);
						map.put(TAG_LINK_IMAGE_PRODUK, link_image_produk);
						map.put(TAG_KOMPOSISI, komposisi);
						map.put(TAG_HARGA, harga);

						// adding HashList to ArrayList
						DaftarProduk.add(map);
					}
				} else {
					// Tidak ada record data (success = 0)
					// akan menutup aplikasi
					finish();
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
			
			return null;
		}

		/**
		 * After completing background task Dismiss the progress dialog
		 */
		@Override
		protected void onPostExecute(String file_url) {
			// TODO Auto-generated method stub
			//super.onPostExecute(file_url);
			// dismiss the dialog after getting all record rumah sakit
			pDialog.dismiss();
			// updating UI from Background Thread
			runOnUiThread(new Runnable() {
				
				@Override
				public void run() {
					// TODO Auto-generated method stub
					// updating listview
					SetListViewAdapter(DaftarProduk);
				}
			});
		}				
	}
	
	/* Initiating Menu XML file (menu_context.xml) */
    public boolean onCreateOptionsMenu(Menu menu)
    {
        MenuInflater menuInflater = getMenuInflater();
        menuInflater.inflate(R.layout.menu_context, menu);
        return true;
    }
    
    /**
     * Event Handling for Individual menu item selected
     * Identify single menu item by it's id
     * */
    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
        
        switch (item.getItemId())
        {
        case R.id.menu_view_cart:
        	// Single menu item is selected do something
        	// Ex: launching new activity/screen or show alert message
            //Toast.makeText(MenuAwal.this, "Bookmark is Selected", Toast.LENGTH_SHORT).show();
        	startActivity(new Intent("com.selly.hanjuang.MenuCart"));
            return true;
        default:
            return super.onOptionsItemSelected(item);
        }
    }
}
